# coding=utf-8
import string
import time
from django.http import JsonResponse

from project.settings import (
    QINIU_accessKey,
    QINIU_secretKey,
    QINIU_videoBucketName,
    QINIU_imgBucketName,
    QINIU_textBucketName,
    QINIU_textBucketDomain,
    USER_TYPE,
)
from qiniu import Auth, BucketManager, put_data
from lib.common import AbstractHandler

qiniuAuth = Auth(QINIU_accessKey, QINIU_secretKey)
bucketMgr = BucketManager(qiniuAuth)

token_expire_time = 60*60*25
check_expire_time = 60*60*1


class BaseHandler(AbstractHandler):
    RES_VIDEO = 'video'
    RES_IMG = 'img'
    RES_TEXT = 'text'

    def __init__(self, app_logger):
        AbstractHandler.__init__(self, app_logger)

        self.random_seeds = string.ascii_lowercase + string.digits
        self.lastGetTokenTimeTab = {self.RES_VIDEO: 0, self.RES_IMG: 0, self.RES_TEXT: 0}
        self.tokenTab = {self.RES_VIDEO: None, self.RES_IMG: None, self.RES_TEXT: None}
        self.bucketTab = {
                             self.RES_VIDEO: QINIU_videoBucketName,
                             self.RES_IMG: QINIU_imgBucketName,
                             self.RES_TEXT: QINIU_textBucketName
        }

        self.METHOD_TAB = {
            'GET':  {
                'getuploadtoken': self.ajax_get_upload_token,
            },
        }

    # def _create_internal_token(self,resource_type):
    #
    #     curTime = time.time()
    #     if self.tokenTab[resource_type]:
    #         if (curTime - self.lastGetTokenTimeTab[resource_type]) < 3600:
    # we have 1 hour to use last token to upload file
    #             self.app_logger.debug('reuse saved token')
    #             return self.tokenTab[resource_type]
    #
    #
    #     #randomString = ''.join(random.choice(self.random_seeds) for i in range(6))
    #     self.tokenTab[resource_type] = qiniuAuth.upload_token(self.bucketTab[resource_type],
    #                                            key=None,
    #                                            expires=7200,
    #
    #                                    )
    #
    #
    #     self.lastGetTokenTimeTab[resource_type] = curTime
    #
    #     return self.tokenTab[resource_type]

    def ajax_get_upload_token(self, request):
        self.checkMandatoryParams(request, ['resource_type'])
        resource_type = request.param_dict['resource_type']
        # self.app_logger.info( 'mgr::get upload token request %s'% resource_type)

        keyprefix = 'def'
        ut = request.session['ut']
        if ut == USER_TYPE.ADMIN:
            keyprefix = 'mgr'
        else:
            if ut == USER_TYPE.TEACHER:
                keyprefix = 'tch_'
            elif ut == USER_TYPE.STDUENT:
                keyprefix = 'stu_'
            elif ut == USER_TYPE.DATAINPUTER:
                keyprefix = 'dit_'
            # id
            keyprefix += str(request.user.id)

        curTime = time.time()
        if self.tokenTab[resource_type]:
            passedTime = curTime - self.lastGetTokenTimeTab[resource_type]
            # 没有过1小时，用缓存的token， 过了就重新生成token， 确保每次获取的token至少可以用24小时
            if passedTime < check_expire_time:
                self.app_logger.debug('passtime: %s, reuse saved token' % passedTime)
                return JsonResponse({'uptoken': self.tokenTab[resource_type]})

        # randomString = ''.join(random.choice(self.random_seeds) for i in range(6))
        self.tokenTab[resource_type] = qiniuAuth.upload_token(self.bucketTab[resource_type],
                                               key=None,
                                               expires=token_expire_time,
                                               policy={
                                                   # 'callbackUrl':"http://wx.121866.com/qiniu/uploadcallback",
                                                   # 'callbackBody':"key=$(key)&name=$(fname)",  #$(etag)
                                                   # 'saveKey':'%s/$(year)$(mon)$(day)$(hour)$(min)$(sec)_$(etag)$(ext)'
                                                   # % keyprefix
                                                   'saveKey': '%s/$(etag)$(ext)' % keyprefix
                                               }
                                       )
        # print self.tokenTab[resource_type]

        self.lastGetTokenTimeTab[resource_type] = curTime

        return JsonResponse({'uptoken': self.tokenTab[resource_type]})

    def get_key_by_url(self, resourceUrl):

        splitPos = resourceUrl.find('/', 8)  # jump to the end of leading http://
        if splitPos < 0:
            err ='unknow resource url format :%s' % resourceUrl
            self.app_logger.error(err)
            return 417, err

        splitPos += 1  # jump to the part behind the /

        return 0, resourceUrl[splitPos:]

    def delete_qiniu_file(self, resourceUrl, file_type):

        self.app_logger.critical('request to delete qiniu %s file %s' % (file_type, resourceUrl))

        if file_type == 'video':
            bucketName = QINIU_videoBucketName
        elif file_type == 'text':
            bucketName = QINIU_textBucketName
        else:
            return 417, "upsupported file type:%s" % file_type

        ret, key_or_err = self.get_key_by_url(resourceUrl)
        if ret != 0:
            return ret, key_or_err

        ret, info = bucketMgr.delete(bucketName, key_or_err)

        return ret, info

    def add_qiniu_text_file(self, fileContent):
        self.app_logger.debug('request to add qiniu text file ')

        token = qiniuAuth.upload_token(QINIU_textBucketName,
                                               key=None,
                                               expires=token_expire_time,
                                               policy={
                                                   # 'callbackUrl':"http://wx.121866.com/qiniu/uploadcallback",
                                                   # 'callbackBody':"key=$(key)&name=$(fname)",  #$(etag)
                                                   'saveKey': 'text/$(etag).html'
                                               })

        ret, info = put_data(token,
                             key=None,
                             data=fileContent,
                             mime_type="text/html")

        if not ret or ('key'not in ret):
            return False, info.error
        else:
            return True, QINIU_textBucketDomain + ret["key"]

    def modify_qiniu_text_file(self, url, fileContent):
        self.app_logger.debug('request to modify qiniu text file ')

        ret, key_or_err = self.get_key_by_url(url)
        if ret != 0:
            return ret, key_or_err

        key = key_or_err

        token = qiniuAuth.upload_token(QINIU_textBucketName, key=key, expires=token_expire_time)

        ret, info = put_data(token,
                             key=key,
                             data=fileContent,
                             mime_type="text/html")
        if not ret or ('key'not in ret):
            return False, info.error
        else:
            return True, QINIU_textBucketDomain + ret["key"]
